<template>
<div class="page-wrapper">
  <Breadcrumb v-bind="breads" />
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-12">
        <div class="card">
          <form @submit.prevent="saveRole" autocomplete="off">
            <div class="card-body">
              <ul class="list-group" style="background-color:#fff;padding:15px;line-height: 35px;">
                <ListItem v-for="(permit, index) in permits" :permits="permits" :index="index" :permit="permit" :key="permit.permitId"
                  :checkedIds="checkedIds" />
              </ul>
            </div>
            <div class="border-top">
              <div class="card-body">
                <button type="submit" id="save-btn" class="btn btn-primary">保 存</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  <Footer />
</div>
</template>
<script>
  import $ from 'jquery'
  import cfg from '../dist/js/config'

  import Footer from './ComFooter'
  import Breadcrumb from './ComBreadcrumb'
  import ListItem from './RolePermitItem'
  import { platforms } from '../dist/js/enum'

  function loadPermits() {
    $.get(cfg.serverPath + '/permit/list/' + this.platform + '/!/' + this.platType + '-set-permit',
      result => {
        if (result.status != 0) {
          $(document).failMsg(result.message)
          return
        }
        if (!result.data) {
          return
        }
        const platPermits = this.sortPermits(result.data)
        for (let platPermit of platPermits) {
          this.permits.push(platPermit) }
        this.loadCrossPermits()
      })
  }
  function loadCrossPermits() {
    $.get(cfg.serverPath + '/permit/list/cross/' + this.platform + '/!/' + this.platType + '-set-permit',
      result => {
        if (result.status != 0) {
          $(document).failMsg(result.message)
          return
        }
        if (!result.data) {
          return
        }
        const crossPermits = this.sortPermits(result.data)
        if (crossPermits.length == 0) {
          return
        }
        for (let permit of this.permits) {
          if (permit.name == '权限中心') {
            for (let corssPermit of crossPermits) {
              permit.permits.push(corssPermit) }
          } }
      })
  }
  function sortPermits(permits) {
    const dstPermits = []
    // 父子归类
    for (let i in permits) {
      if (!permits[i].permits) {
        permits[i].permits = [];
        permits[i].auths = []
      }
      for (let j in permits) {
        if (permits[j].parentId && permits[i].permitId == permits[j].parentId) {
          if (permits[j].isMenu) {
            permits[i].permits.push(permits[j]);
          } else {
            permits[i].auths.push(permits[j]);
          }
        }
      }
      if (!permits[i].parentId) {
        dstPermits.unshift(permits[i]);
      }
    }
    // 顶级排序
    dstPermits.sort((a, b) => {
      return a.sort - b.sort
    })
    // 子级排序
    sort(dstPermits)

    return dstPermits
  }
  function sort(list) {
    for (let item of list) {
      item.permits.sort((a, b) => {
        return a.sort - b.sort
      })
      item.auths.sort((a, b) => {
        return a.sort - b.sort
      })
      sort(item.permits)
      sort(item.auths) }
  }
  function loadRole() {
    const search = {
      roleId: this.roleId,
      pageSize: 1
    }
    $.get(cfg.serverPath + '/role/page/' + this.platform + '/!/' + this.platType + '-set-permit',
      search,
      result => {
        if (result.status != 0) {
          $(document).failMsg(result.message)
          return
        }
        let role = result.data.list[0]
        if (role.permits) {
          this.checkedIds = role.permits.split(',')
        }
      })
  }
  function saveRole(event) {
    const $target = $(event.target)
    if (!$target.lock()) {
      return
    }
    const checkedIds = $target.find(':checkbox:checked').map(function(i, el) {
      return $(el).val()
    }).get().join(',')
    const role = {
      roleId: this.roleId,
      permits: checkedIds
    }
    $.ajax({
      contentType: 'application/json; charset=UTF-8',
      url: cfg.serverPath + '/role/edit/' + this.platform + '/!/' + this.platType + '-set-permit',
      type: 'patch',
      data: JSON.stringify(role),
      success: result => {
        if (result.status != 0) {
          $target.failMsg(result.message)
          return
        }
        $target.infoMsg('保存成功')
        this.$router.go(-1)
      }
    })
  }
  function breads() {
    return {
      title: '权限分配',
      items: [
        {
          href: '#/',
          name: '主页'
        }, {
          href: '',
          name: '角色管理'
        },
        {
          href: '',
          name: '权限分配'
        }
      ]
    }
  }
  export default {
    components: {
      Footer,
      Breadcrumb,
      ListItem
    },
    props: {
      roleId: String,
      platType: String
    },
    data() {
      return {
        platform: -1,
        permits: [],
        checkedIds: []
      }
    },
    methods: {
      loadPermits,
      loadCrossPermits,
      sortPermits,
      loadRole,
      saveRole
    },
    created() {
      for (let i in platforms) {
        if (platforms[i].name.toLowerCase().indexOf(this.platType) != -1) {
          this.platform = i
          break
        }
      }
      this.loadPermits()
      this.loadRole()
    },
    computed: {
      breads
    }
  }
</script>